package com.maxd.service.cash;

import com.maxd.error.Result;
import com.maxd.error.ResultUtil;
import com.maxd.model.CommonInfo;
import com.maxd.model.MessageInfo;
import com.maxd.model.PublisherOrderDtoBean;
import com.maxd.model.UserInfo;
import com.maxd.respository.cash.CashJpaRepository;
import com.maxd.respository.cash.CashRepository;
import com.maxd.respository.common.CommonRepository;
import com.maxd.respository.order.OrderJpaRepository;
import com.maxd.respository.order.OrderRepository;
import com.maxd.respository.userinfo.UserJpaRepository;
import com.maxd.respository.userinfo.UserRepository;
import com.maxd.service.message.IMessageService;
import com.maxd.service.money.IMoneyDetailsService;
import com.maxd.service.userinfo.UserServiceImpl;
import com.maxd.service.wx.AccountService;
import com.maxd.utils.Config;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import weixin.popular.bean.message.templatemessage.TemplateMessageItem;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 提现的service实现类
 */
@Service
public class CashServiceImpl implements ICashService {
    private Logger logger = LoggerFactory.getLogger(CashServiceImpl.class);
    @Autowired
    private CashJpaRepository cashJpaRepository;
    @Autowired
    private CashRepository cashRepository;
    @Autowired
    private OrderJpaRepository orderJpaRepository;
    @Autowired
    private CommonRepository commonRepository;
    @Autowired
    private OrderRepository orderRepository;
    @Autowired
    private UserRepository userRepository;
    @Autowired
    private IMoneyDetailsService iMoneyDetailsService;
    @Autowired
    private AccountService accountService;
    @Autowired
    private IMessageService iMessageService;
    @Autowired
    private UserServiceImpl userService;

    @Override
    public Result findOne(long id) {
        return ResultUtil.success(cashJpaRepository.findById(id).orElse(null));
    }

    @Override
    public Result delete(long id) {
        cashJpaRepository.deleteById(id);
        return ResultUtil.success();
    }

    @Override
    public Result findOne(String relationId) {
        return ResultUtil.success(cashRepository.findOne(relationId));
    }

    @Override
    public Result selectCashOutList(String id) {
        return ResultUtil.success(cashRepository.selectCashOutList(id));
    }


    @Override
    public Result findByPhone(String phone) {
        return ResultUtil.success(cashRepository.findByPhone(phone));
    }

    @Override
    @Transactional
    public Result updateIsOut(Boolean isOut, Long id) {
        return ResultUtil.success(cashRepository.updateIsOut(isOut, id));
    }

    @Override
    public Result userToTalMoney() {
        cashTotal(null);
        return ResultUtil.success();
    }

    @Override
    public Result userToTalMoneys(Integer month) {
        cashTotal(month);
        return ResultUtil.success();
    }

    /**
     * 结算业务
     */
    private void cashTotal(Integer month) {
        CommonInfo url = commonRepository.findOne(19);
        DecimalFormat df = new DecimalFormat("#########.##");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Calendar cal = Calendar.getInstance();
        if(month==null){
//            cal.add(Calendar.MONTH, -1);
        }else{
            cal.set(Calendar.MONTH, month);
        }
        Date date3 = cal.getTime();
        String format1 = sdf.format(date3);
        List<Map<String, Object>> topInvitationMoney = orderRepository.selectTopInvitationMoney(format1, 3);
        List<Map<String, Object>> invitationMoney = orderRepository.selectInvitationMoney(format1, 3);
        List<Map<String, Object>> invitationMoneys = orderRepository.selectInvitationMoneys(format1, 3);
            orderRepository.updateOrderBalance(format1, 3,1);
            if(topInvitationMoney!=null && topInvitationMoney.size()>0){
                //计算直属
                for(Map<String, Object> map:topInvitationMoney){
                    try{
                        String relationId=String.valueOf(map.get("top_relation_id"));
                        String relationMoney=String.valueOf(map.get("money"));
                        UserInfo invitation = userRepository.getUserByRelationId(relationId);
                        if (StringUtils.isNotBlank(relationMoney)&& invitation!=null) {
                            String format = df.format(Double.parseDouble(relationMoney));
                            userRepository.updateJiFenAdd(format, invitation.getId());
                            iMoneyDetailsService.saveBody(invitation.getId(), 1, 1, sdf.format(date3) +"顶级团长佣金结算", "上月【确认收货订单】佣金结算，成员：" + invitation.getNickName() + ",佣金金额：" + format, Double.parseDouble(format));
                            two2Success(invitation.getOpenId(), invitation.getNickName(), sdf1.format(new Date()), format, df.format(Double.parseDouble(invitation.getJifen())), url.getValue());
                            logger.error(invitation.getRelationId() + "--invitation can cash money ");
                        }
                    }catch (Exception e){
                        e.printStackTrace();
                        logger.error(e.getMessage());
                    }
                }
            }
            if(invitationMoney!=null && invitationMoney.size()>0){
                //计算直属
                for(Map<String, Object> map:invitationMoney){
                    try{
                        String relationId=String.valueOf(map.get("invitation"));
                        String relationMoney=String.valueOf(map.get("money"));
                        UserInfo invitation = userRepository.getUserByRelationId(relationId);
                        if (StringUtils.isNotBlank(relationMoney)&& invitation!=null) {
                            String format = df.format(Double.parseDouble(relationMoney));
                            userRepository.updateJiFenAdd(format, invitation.getId());
                            iMoneyDetailsService.saveBody(invitation.getId(), 1, 1, sdf.format(date3) +"直属佣金结算", "上月【确认收货订单】佣金结算，成员：" + invitation.getNickName() + ",佣金金额：" + format, Double.parseDouble(format));
                            two2Success(invitation.getOpenId(), invitation.getNickName(), sdf1.format(new Date()), format, df.format(Double.parseDouble(invitation.getJifen())), url.getValue());
                            logger.error(invitation.getRelationId() + "--invitation can cash money ");
                        }
                    }catch (Exception e){
                        e.printStackTrace();
                        logger.error(e.getMessage());
                    }
                }
            }
            if(invitationMoneys!=null && invitationMoneys.size()>0){
                //计算非直属
                for(Map<String, Object> map:invitationMoneys){
                    try {
                        String relationId=String.valueOf(map.get("invitations"));
                        String relationMoney=String.valueOf(map.get("money"));
                        UserInfo invitation = userRepository.getUserByRelationId(relationId);
                        if (StringUtils.isNotBlank(relationMoney)&& invitation!=null) {
                            String format = df.format(Double.parseDouble(relationMoney));
                            userRepository.updateJiFenAdd(format, invitation.getId());
                            iMoneyDetailsService.saveBody(invitation.getId(), 1, 1, sdf.format(date3) +"非直属佣金结算", "上月【确认收货订单】佣金结算，成员：" + invitation.getNickName() + ",佣金金额：" + format, Double.parseDouble(format));
                            threeSuccess(invitation.getOpenId(), invitation.getNickName(), sdf1.format(new Date()), format, df.format(Double.parseDouble(invitation.getJifen())), url.getValue());
                            logger.error(invitation.getRelationId() + "--invitations can cash money ");
                        }
                    }catch (Exception e){
                        e.printStackTrace();
                        logger.error(e.getMessage());
                    }

                }

        }

    }
//    private void cashTotal(Integer month) {
//        CommonInfo url = commonRepository.findOne(19);
//        DecimalFormat df = new DecimalFormat("#########.##");
//        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
//        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//        Calendar cal = Calendar.getInstance();
//        if(month==null){
//            cal.add(Calendar.MONTH, -1);
//        }else{
//            cal.set(Calendar.MONTH, month);
//        }
//        Date date3 = cal.getTime();
//        CommonInfo one = commonRepository.findOne(91);
//        String format1 = sdf.format(date3);
//        if("1".equals(one.getValue())){
//            //获取用户本身佣金
//            List<Map<String, Object>> relationIdMoney = orderRepository.selectRelationIdMoney(format1, 3);
//            //获取作为的团长佣金
//            List<Map<String, Object>> invitationMoney = orderRepository.selectInvitationMoney(format1, 3);
//            orderRepository.updateOrderBalance(format1, 3,1);
//            //计算用户本身佣金
//            for(Map<String, Object> map:relationIdMoney){
//                String invitation=String.valueOf(map.get("relation_id"));
//                String relationMoney=String.valueOf(map.get("money"));
//                UserInfo userInfo = userRepository.getUserByRelationId(invitation);
//                if (StringUtils.isNotBlank(relationMoney)&& userInfo!=null) {
//                    String format = df.format(Double.parseDouble(relationMoney));
//                    userRepository.updateJiFenAdd(format, userInfo.getId());
//                    UserInfo save = userRepository.getUserByRelationId(String.valueOf(invitation));
//                    iMoneyDetailsService.saveBody(userInfo.getId(), 1, 1, sdf.format(date3) + "结算", "上月【确认收货订单】结算金额：" + format, Double.parseDouble(format));
//                    totalSuccess(userInfo.getOpenId(), save.getNickName(), sdf1.format(new Date()), df.format(Double.parseDouble(save.getJifen())), df.format(Double.parseDouble(save.getJifen())), url.getValue());
//                    logger.error(userInfo.getRelationId() + "--user can cash money " + save.getJifen());
//                }
//            }
//            //计算作为团长佣金
//            for(Map<String, Object> map:invitationMoney){
//                String relationId=String.valueOf(map.get("invitation"));
//                String relationMoney=String.valueOf(map.get("money"));
//                UserInfo invitation = userRepository.getUserByRelationId(relationId);
//                if (StringUtils.isNotBlank(relationMoney)&& invitation!=null) {
//                    String format = df.format(Double.parseDouble(relationMoney));
//                    userRepository.updateJiFenAdd(format, invitation.getId());
//                    iMoneyDetailsService.saveBody(invitation.getId(), 1, 1, sdf.format(date3) +"团长佣金结算", "上月【确认收货订单】佣金结算，成员：" + invitation.getNickName() + ",佣金金额：" + format, Double.parseDouble(format));
//                    twoSuccess(invitation.getOpenId(), invitation.getNickName(), sdf1.format(new Date()), format, df.format(Double.parseDouble(invitation.getJifen())), url.getValue());
//                    logger.error(invitation.getRelationId() + "--invitation can cash money ");
//                }
//            }
//        }else{
//            List<Map<String, Object>> relationIdMoney = orderRepository.selectRelationIdMoney(format1, 3);
//            List<Map<String, Object>> invitationMoney = orderRepository.selectInvitationMoney(format1, 3);
//            List<Map<String, Object>> invitationMoneys = orderRepository.selectInvitationMoneys(format1, 3);
//            orderRepository.updateOrderBalance(format1, 3,1);
//            //计算自己本身佣金
//            if(relationIdMoney!=null && relationIdMoney.size()>0){
//                for(Map<String, Object> map:relationIdMoney){
//                    try {
//                        String invitation=String.valueOf(map.get("relation_id"));
//                        String relationMoney=String.valueOf(map.get("money"));
//                        UserInfo userInfo = userRepository.getUserByRelationId(invitation);
//                        if (StringUtils.isNotBlank(relationMoney)&& userInfo!=null) {
//                            String format = df.format(Double.parseDouble(relationMoney));
//                            userRepository.updateJiFenAdd(format, userInfo.getId());
//                            UserInfo save = userRepository.getUserByRelationId(String.valueOf(invitation));
//                            iMoneyDetailsService.saveBody(userInfo.getId(), 1, 1, sdf.format(date3) + "结算", "上月【确认收货订单】结算金额：" + format, Double.parseDouble(format));
//                            totalSuccess(userInfo.getOpenId(), save.getNickName(), sdf1.format(new Date()), df.format(Double.parseDouble(save.getJifen())), df.format(Double.parseDouble(save.getJifen())), url.getValue());
//                            logger.error(userInfo.getRelationId() + "--user can cash money " + save.getJifen());
//                        }
//                    }catch (Exception e){
//                        e.printStackTrace();
//                        logger.error(e.getMessage());
//                    }
//
//                }
//            }
//            if(invitationMoney!=null && invitationMoney.size()>0){
//                //计算直属
//                for(Map<String, Object> map:invitationMoney){
//                    try{
//                        String relationId=String.valueOf(map.get("invitation"));
//                        String relationMoney=String.valueOf(map.get("money"));
//                        UserInfo invitation = userRepository.getUserByRelationId(relationId);
//                        if (StringUtils.isNotBlank(relationMoney)&& invitation!=null) {
//                            String format = df.format(Double.parseDouble(relationMoney));
//                            userRepository.updateJiFenAdd(format, invitation.getId());
//                            iMoneyDetailsService.saveBody(invitation.getId(), 1, 1, sdf.format(date3) +"直属佣金结算", "上月【确认收货订单】佣金结算，成员：" + invitation.getNickName() + ",佣金金额：" + format, Double.parseDouble(format));
//                            two2Success(invitation.getOpenId(), invitation.getNickName(), sdf1.format(new Date()), format, df.format(Double.parseDouble(invitation.getJifen())), url.getValue());
//                            logger.error(invitation.getRelationId() + "--invitation can cash money ");
//                        }
//                    }catch (Exception e){
//                        e.printStackTrace();
//                        logger.error(e.getMessage());
//                    }
//                }
//            }
//            if(invitationMoneys!=null && invitationMoneys.size()>0){
//                //计算非直属
//                for(Map<String, Object> map:invitationMoneys){
//                    try {
//                        String relationId=String.valueOf(map.get("invitations"));
//                        String relationMoney=String.valueOf(map.get("money"));
//                        UserInfo invitation = userRepository.getUserByRelationId(relationId);
//                        if (StringUtils.isNotBlank(relationMoney)&& invitation!=null) {
//                            String format = df.format(Double.parseDouble(relationMoney));
//                            userRepository.updateJiFenAdd(format, invitation.getId());
//                            iMoneyDetailsService.saveBody(invitation.getId(), 1, 1, sdf.format(date3) +"非直属佣金结算", "上月【确认收货订单】佣金结算，成员：" + invitation.getNickName() + ",佣金金额：" + format, Double.parseDouble(format));
//                            threeSuccess(invitation.getOpenId(), invitation.getNickName(), sdf1.format(new Date()), format, df.format(Double.parseDouble(invitation.getJifen())), url.getValue());
//                            logger.error(invitation.getRelationId() + "--invitations can cash money ");
//                        }
//                    }catch (Exception e){
//                        e.printStackTrace();
//                        logger.error(e.getMessage());
//                    }
//
//                }
//            }
//
//        }
//
//    }


    /**
     * 结算成功通知
     *
     * @param openId
     * @param date
     * @param money
     * @param totalMoney
     * @param url
     */
    private void totalSuccess(String openId, String name, String date, String money, String totalMoney, String url) {
        try{
            UserInfo userByWxId = userRepository.getUserByWxId(openId);
            MessageInfo messageInfo = new MessageInfo();
            messageInfo.setState(String.valueOf(4));
            messageInfo.setContent(name + " 您好！您上月【确认收货订单】结算信息如下，请尽快申请提现！结算金额【" + money + "】进入【我的】点击【可提现金额】申请提现");
            messageInfo.setTitle("本月结算通知");
            messageInfo.setUserName(userByWxId.getNickName());
            messageInfo.setUserId(String.valueOf(userByWxId.getId()));
            iMessageService.saveBody(messageInfo);
            if (userByWxId.getClientid() != null) {
                userService.pushToSingle("本月结算通知", name + " 您好！您上月【确认收货订单】结算信息如下，请尽快申请提现！结算金额【" + money + "】进入【我的】点击【可提现金额】申请提现", userByWxId.getClientid());
            }

            CommonInfo three = commonRepository.findOne(37);
            String apkey = Config.JieSuanNotification;
            if (three != null) {
                apkey = three.getValue();
            }

            LinkedHashMap<String, TemplateMessageItem> data = new LinkedHashMap<>();
            data.put("thing1", new TemplateMessageItem("您好！您上月【确认收货订单】结算信息", "#d71345"));
            data.put("amount4", new TemplateMessageItem(money+ " 元", "#d71345"));
            accountService.sendWxMessage(apkey, data, openId, url);
        }catch (Exception e){
            e.printStackTrace();
            logger.error("openId一致！！！！！"+openId);
        }
    }


    private void twoSuccess(String openId, String name, String date, String money, String totalMoney, String url) {
        try{
            UserInfo userByWxId = userRepository.getUserByWxId(openId);
            MessageInfo messageInfo = new MessageInfo();
            messageInfo.setState(String.valueOf(4));
            messageInfo.setContent(name + " 您好！您上月【团长佣金】结算信息如下，请尽快申请提现！结算金额【" + money + "】进入【我的】点击【可提现金额】申请提现");
            messageInfo.setTitle("团长佣金结算通知");
            messageInfo.setUserName(userByWxId.getNickName());
            messageInfo.setUserId(String.valueOf(userByWxId.getId()));
            iMessageService.saveBody(messageInfo);
            if (userByWxId.getClientid() != null) {
                userService.pushToSingle("团长佣金结算通知", name + " 您好！您上月【团长佣金】结算信息如下，请尽快申请提现！结算金额【" + money + "】进入【我的】点击【可提现金额】申请提现", userByWxId.getClientid());
            }

            CommonInfo three = commonRepository.findOne(37);
            String apkey = Config.JieSuanNotification;
            if (three != null) {
                apkey = three.getValue();
            }

            LinkedHashMap<String, TemplateMessageItem> data = new LinkedHashMap<>();
            data.put("thing1", new TemplateMessageItem("您好！您上月【团长佣金】结算信息", "#d71345"));
            data.put("amount4", new TemplateMessageItem(money + " 元", "#d71345"));
            accountService.sendWxMessage(apkey, data, openId, url);
        }catch (Exception e){
            e.printStackTrace();
            logger.error("openId一致！！！！！"+openId);
        }

    }

    private void two2Success(String openId, String name, String date, String money, String totalMoney, String url) {
        try{
            UserInfo userByWxId = userRepository.getUserByWxId(openId);
            MessageInfo messageInfo = new MessageInfo();
            messageInfo.setState(String.valueOf(4));
            messageInfo.setContent(name + " 您好！您上月【直属佣金】结算信息如下，请尽快申请提现！结算金额【" + money + "】进入【我的】点击【可提现金额】申请提现");
            messageInfo.setTitle("直属佣金结算通知");
            messageInfo.setUserName(userByWxId.getNickName());
            messageInfo.setUserId(String.valueOf(userByWxId.getId()));
            iMessageService.saveBody(messageInfo);
            if (userByWxId.getClientid() != null) {
                userService.pushToSingle("直属佣金结算通知", name + " 您好！您上月【直属佣金】结算信息如下，请尽快申请提现！结算金额【" + money + "】进入【我的】点击【可提现金额】申请提现", userByWxId.getClientid());
            }

            CommonInfo three = commonRepository.findOne(37);
            String apkey = Config.JieSuanNotification;
            if (three != null) {
                apkey = three.getValue();
            }

            LinkedHashMap<String, TemplateMessageItem> data = new LinkedHashMap<>();
            data.put("thing1", new TemplateMessageItem("您好！您上月【直属佣金】结算信息", "#d71345"));
            data.put("amount4", new TemplateMessageItem(money + " 元", "#d71345"));
            accountService.sendWxMessage(apkey, data, openId, url);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    private void threeSuccess(String openId, String name, String date, String money, String totalMoney, String url) {
        try {
            UserInfo userByWxId = userRepository.getUserByWxId(openId);
            MessageInfo messageInfo = new MessageInfo();
            messageInfo.setState(String.valueOf(4));
            messageInfo.setContent(name + " 您好！您上月【非直属佣金】结算信息如下，请尽快申请提现！结算金额【" + money + "】进入【我的】点击【可提现金额】申请提现");
            messageInfo.setTitle("非直属佣金结算通知");
            messageInfo.setUserName(userByWxId.getNickName());
            messageInfo.setUserId(String.valueOf(userByWxId.getId()));
            iMessageService.saveBody(messageInfo);
            if (userByWxId.getClientid() != null) {
                userService.pushToSingle("非直属佣金结算通知", name + " 您好！您上月【非直属佣金】结算信息如下，请尽快申请提现！结算金额【" + money + "】进入【我的】点击【可提现金额】申请提现", userByWxId.getClientid());
            }

            CommonInfo three = commonRepository.findOne(37);
            String apkey = Config.JieSuanNotification;
            if (three != null) {
                apkey = three.getValue();
            }

            LinkedHashMap<String, TemplateMessageItem> data = new LinkedHashMap<>();
            data.put("thing1", new TemplateMessageItem("您好！您上月【非直属佣金】结算信息", "#d71345"));
            data.put("amount4", new TemplateMessageItem(money + " 元", "#d71345"));
            accountService.sendWxMessage(apkey, data, openId, url);
        }catch (Exception e){
            e.printStackTrace();
        }

    }

}
